package com.ftg.learn.util;

import com.alibaba.fastjson2.JSONObject;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * jwt
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/4/27 上午9:45
 */
public class JwtUtil {

    private static final Logger log = LoggerFactory.getLogger(JwtUtil.class);

    private static final String salt = "adminkjx";;

    /**
     * 生成密钥
     * @return
     */
    private static SecretKey createKey(){
        //把我们的盐转换成byte[]
        byte[] bytes = Base64.getDecoder().decode(salt);
        //密钥
        SecretKey key = new SecretKeySpec(bytes, "AES");
        return key;
    }

    /**
     * 生成三分钟以后过期
     * @return
     */
    private static Date expireData(){
        //时间戳
        long nowMillis = System.currentTimeMillis();
        //一小时
        long diff = 30 *60 *1000;
        //时间
        Date now = new Date(nowMillis + diff);
        return now;
    }

    /**
     * 生成我们的token
     * @param id      用户的编号
     * @param account 账号
     * @return  STrign token
     */
    public static String createjwtToken(Integer id,String account) {
        JwtBuilder jwt = Jwts.builder()
                .claim("id",id)
                .claim("account",account)
                .setExpiration(expireData()).signWith(SignatureAlgorithm.HS256,createKey());
        String token = jwt.compact();
        return token;
    }

    /**
     * 如果出现异常，表示当前的token要么过期，要么伪造的
     * @param token
     * @return
     */
    public static Claims verifyJwtToken(String token) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException{
        return Jwts.parser().setSigningKey(createKey()).parseClaimsJws(token).getBody();
    }

}
